package acme.ws;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import acme.db.CrudDao;
import acme.db.DaoFactory;
import acme.entity.DailyDeal;
import acme.entity.Product;


public class DailyDealServlet extends JSONServlet {
	
	private static final long serialVersionUID = 7793392317087332094L;
	
	private static Random random = new Random();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		Product product = getRandomProduct();
		DailyDeal dailyDeal = getDailyDeal(product);
		this.returnJSON(dailyDeal, resp);
	}

	public static Product getRandomProduct(){
		CrudDao<Product> pDao = DaoFactory.getProductDAO();
		Collection<Product> products = pDao.getAllResources();
		List<Product> list = new ArrayList<Product>(products);
		int index = Integer.parseInt( Math.round( ((list.size() - 1) * random.nextDouble()) ) + "" );
		Product p = list.get(index);
		return p;
	}

	public static DailyDeal getDailyDeal(Product product){
		String id = random.nextInt(10000) + "";
		String discount = (random.nextInt(100) / 100) + "";
		DailyDeal dailyDeal = new DailyDeal(id, product, discount);
		return dailyDeal;
	}
}
